package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
)

func init() {
	logFile, err := os.OpenFile("./访问日志.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		panic(err)
	}

	log.SetOutput(logFile)
}

func logRequest(req *http.Request, status int) {
	l := fmt.Sprintf("client IP: %v\tstatus: %v", req.RemoteAddr, status)
	log.Print(l)
	fmt.Println(l)
}

func healthz(w http.ResponseWriter, req *http.Request) {
	w.WriteHeader(http.StatusOK)

	logRequest(req, http.StatusOK)
}

func headers(w http.ResponseWriter, req *http.Request) {
	htmlString := ""
	version := os.Getenv("VERSION")
	w.Header().Add("VERSION", version)
	htmlString += fmt.Sprintf("VERSION: %v\n", version)
	for name, headers := range req.Header {
		for _, h := range headers {
			w.Header().Add(name, h)
			htmlString += fmt.Sprintf("%v: %v\n", name, h)
		}
	}

	w.WriteHeader(http.StatusAccepted)

	fmt.Fprint(w, htmlString)
	logRequest(req, http.StatusAccepted)
}

func main() {
	http.HandleFunc("/healthz", healthz)
	http.HandleFunc("/", headers)

	http.ListenAndServe(":8080", nil)
}
